Java ConcurrentMap
part 13/19 · 30.6 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
There is no way for ConcurrentMaps to lock the entire table. There is no possibility of ConcurrentModificationException as there is with inadvertent concurrent modification of non-concurrent Maps. The size() method may take a long time, as opposed to the corresponding non-concurrent Maps and other collections which usually include a size field for fast access, because they may need to scan the entire Map in some way. When concurrent modifications are occurring, the results reflect the state of the Map at some time, but not necessarily a single consistent state, hence size(), isEmpty() and containsValue(java.lang.Object) may be best used only for monitoring.
ConcurrentMap 1.5 methods
There are some operations provided by ConcurrentMap that are not in Map - which it extends - to allow atomicity of modifications. The replace(K, v1, v2) will test for the existence of v1 in the Entry identified by K and only if found, then the v1 is replaced by v2 atomically. The new replace(k,v) will do a put(k,v) only if k is already in the Map. Also, putIfAbsent(k,v) will do a put(k,v) only if k is not already in the Map, and remove(k, v) will remove the Entry for v only if v is present. This atomicity can be important for some multi-threaded use cases, but is not related to the weak-consistency constraint.
For ConcurrentMaps, the following are atomic.
m.putIfAbsent(k, v) is atomic but equivalent to:
if (k == null || v == null)
throw new NullPointerException();
if (!m.containsKey(k)) {
return m.put(k, v);
} else {
return m.get(k);
}
m.replace(k, v) is atomic but equivalent to:
if (k == null || v == null)
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────